import { Pagination, Form, Input, Button, Table, Popconfirm, Space, Tree, Select, Modal, message } from 'antd'
// import '../Role_management/role_management.scss'
import './orgTable.scss'
import http from '../../utils/http'
import { useEffect, useState } from 'react';
import store from '../../store/index'
const { Option } = Select;
const editlayout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 14,
    },
};
const tailLayout = {
    wrapperCol: {
        offset: 8,
        span: 16,
    },
};
const OrgTable = ({ setState }) => {
    const layout = {
        labelCol: {
            span: 16,
        },
        wrapperCol: {
            span: 16,
        },
    };
    const [form] = Form.useForm();
    const [editForm] = Form.useForm();
    const [searchForm] = Form.useForm();
    const xinzeng = () => {
        setState(2)
    }
    //后端时间戳转时间的方法
    const toTimes = (value) => {
        if (value) {
            let date = new Date(value)
            let y = date.getFullYear()  //获取年份
            let m = date.getMonth() + 1  //获取月份
            m = m < 10 ? "0" + m : m  //月份不满10天显示前加0
            let d = date.getDate()  //获取日期
            d = d < 10 ? "0" + d : d  //日期不满10天显示前加0
            return y + "-" + m + "-" + d
        }
        else {
            return null
        }
    }
    const resize = () => {
        searchForm.getFieldsValue(true).orgname = ''
        searchForm.getFieldsValue(true).orgtype = ''
        getData()
    }
    //修改id
    const [editId, seteditId] = useState(0)
    const onFinish = (values) => {
        values.orId = editId
        values.orType = values.orType == '地区' ? 0 : values.orType == '部门' ? 1 : 2
        console.log(values);
        http({
            url: '/orgmanage/updateorgmanage',
            method: 'post',
            data: values
        }).then((res) => {
            if (res.code === 200) {
                getData()
                form.resetFields();
                seteditModel(false)
            }

        })
    };
    const quxiao = () => {
        seteditModel(false)
    }
    //获取数据
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    useEffect(() => {
        getData()
    }, [])
    const getData = () => {
        http({
            url: '/orgmanage/orgManageList'
            // url: '/Alarules/alaRulesList'
        }).then((res) => {
            console.log(res)
            if (res.code === 200) {
                setTotal(res.data.total)
                if (res.data.records) {
                    let arr = res.data.records.map((v, i) => {
                        return {
                            key: v.orId,
                            orName: v.orName,
                            orType: v.orType == 0 ? '地区' : v.orType == 1 ? '部门' : '处室',
                            orNum: v.orNum,
                            orCreatetime: toTimes(v.orCreatetime),
                            orUpdatetime: toTimes(v.orUpdatetime),
                            orState:v.orState
                        }
                    })
                    setData(arr);
                    // sessionStorage.setItem('roleTable', JSON.stringify(arr));
                }
            }
        })
    }
    const [typeInp, settypeInp] = useState('');
    const search = () => {
        let nameInp = searchForm.getFieldsValue(true).orgname
        nameInp = nameInp == undefined ? '' : nameInp
        let type = typeInp == undefined ? '' : typeInp
        settypeInp(type)
        console.log('orName', nameInp, 'orType', typeInp)
        let chajson = { 'orName': nameInp, 'orType': typeInp }
        console.log(chajson)
        http({
            url: '/orgmanage/orgManageList',
            // method: 'post',
            params: chajson
        }).then((res) => {
            console.log('cha', res)
            if (res.data.records) {
                let arr = res.data.records.map((v, i) => {
                    return {
                        key: v.orId,
                        orName: v.orName,
                        orType: v.orType == 0 ? '地区' : v.orType == 1 ? '部门' : '处室',
                        orNum: v.orNum,
                        orCreatetime: toTimes(v.orCreatetime),
                        orUpdatetime: toTimes(v.orUpdatetime)
                    }
                })
                setData(arr);
                // sessionStorage.setItem('roleTable', JSON.stringify(arr));
            }
            else {
                setData([]);
            }
        })
    }
    const [editModel, seteditModel] = useState(false)
    const openEditBox = (a, b) => {
        //获取当前时间
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth() + 1;
        mm = mm < 10 ? '0' + mm : mm
        let dd = new Date().getDate();
        dd = dd < 10 ? '0' + dd : dd
        let gettime = yy + "-" + mm + "-" + dd;
        console.log(a, b, gettime)
        editForm.setFieldsValue({
            orName: b.orName,
            orType: b.orType,
            orNum: b.orNum,
            orCreatetime: b.orCreatetime,
            orUpdatetime: b.orUpdatetime
        })
        seteditModel(true)
        seteditId(b.key)
    }
    const edithideModal = () => {
        seteditModel(false)
    }
    function cancel(e) {
    }
    //删除按钮
    function confirm(a, b) {
        let id = [];
        if (b) {
            id.push(b.key)
        } else {
            id = newSelectData.map(v => v.key)
        }
        console.log(id)
        http({
            url: '/orgmanage/deleteOrgManage',
            method: 'post',
            data: id
        }).then((res) => {
            console.log(res)
            if (res.code === 200) {
                message.success('删除成功！');
                getData()
            }
        })
        // console.log('id',id)
        setselectedRowKeys([])
    }
    const columns = [
        {
            title: '组织名称',
            dataIndex: 'orName',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '组织类型',
            dataIndex: 'orType',
        },
        {
            title: '组织编号',
            dataIndex: 'orNum',
        },
        {
            title: '创建时间',
            dataIndex: 'orCreatetime',
        },
        {
            title: '更新时间',
            dataIndex: 'orUpdatetime',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => { openEditBox(text, record) }}>修改</a>
                    <Popconfirm
                        title="确定要删除吗?"
                        onConfirm={() => { confirm(text, record) }}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a href="#">删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    //树形结构
    const treeData = [
        {
            title: '乐清市',
            key: '0-0',
            children: [
                {
                    title: '市府办',
                    key: '0-0-0',
                    children: [
                        {
                            title: '统计局',
                            key: '0-0-0-0',
                        },
                        {
                            title: '发展改革处',
                            key: '0-0-0-1',
                        },
                    ],
                },
                {
                    title: '经信局',
                    key: '0-0-1',
                    children: [
                        {
                            title: '办公室',
                            key: '0-0-1-0',
                        },
                        {
                            title: '企业科',
                            key: '0-0-1-1',
                        },
                        {
                            title: '经济运行科',
                            key: '0-0-1-2',
                        },
                        {
                            title: '数字化推进科',
                            key: '0-0-1-3',
                        },
                        {
                            title: '产业人才科',
                            key: '0-0-1-4',
                        },
                        {
                            title: '投资机装科',
                            key: '0-0-1-5',
                        },
                    ],
                },
                {
                    title: '组织部',
                    key: '0-0-2',
                    children: [
                        {
                            title: '宣传部',
                            key: '0-0-2-0',
                        },
                        {
                            title: '文化部',
                            key: '0-0-2-1',
                        },
                    ],
                },
            ],
        },
    ];

    const [newSelectData, setnewSelectData] = useState([])
    const [selectedRowKeys, setselectedRowKeys] = useState([])
    const rowSelection = {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            setselectedRowKeys(selectedRowKeys)
            setnewSelectData(selectedRows)
        },
        getCheckboxProps: (record) => (
            // console.log('record',record),
            {
            // disabled: record.orState === 0,
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    function handleChange(value) {
        // console.log(`selected ${value}`);
        settypeInp(value)
    }
    //改变页码
    function onChange(pageNumber) {
        console.log('Page: ', pageNumber);
    }
    return <div className='org'>
        <div>
            <p>组织树新增</p>
            <Tree treeData={treeData}
                defaultExpandAll className='tree'></Tree>
        </div>
        <div className='roleContent'>
            <Form form={form} name="horizontal_login" layout="inline" className='title'>
                <Form.Item
                >
                    <div className='kuai'>
                        <span></span>
                        <span>组织信息管理</span>
                    </div>
                </Form.Item>
                <Form.Item className='btn'>
                    <div>
                        <Button className='cha'
                            type="primary"
                            onClick={xinzeng}>新增</Button>
                        <Popconfirm title="确定要将他们全部删除吗？"
                            onConfirm={() => { confirm() }}
                            onCancel={cancel} okText="Yes" cancelText="No">
                            <a href="#"><Button className='resize' type="primary">批量删除</Button></a></Popconfirm>
                    </div>

                </Form.Item>
            </Form>
            <div className='biao'>
                <Form {...layout} form={searchForm} name="horizontal_login" layout="inline" className='Role'>
                    <Form.Item
                        name="orgname"
                        label='组织名称'
                    ><Input placeholder='请输入组织名称' />
                    </Form.Item>
                    <Form.Item
                        name="orgtype"
                        label='组织类型'
                    > <Select
                        placeholder="请选择"
                        allowClear
                        style={{ width: '100px' }}
                        onChange={handleChange}
                    >
                            <Option value="0">地区</Option>
                            <Option value="1">部门</Option>
                            <Option value="2">处室</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item className='btn'>
                        <div>
                            <Button className='cha'
                                type="primary"
                                onClick={search}>查询</Button>
                            <Button className='resize' onClick={resize} type="primary">重置</Button>
                        </div>

                    </Form.Item>
                </Form>
                <Table className='table1'
                    rowSelection={{
                        ...rowSelection,
                    }}
                    columns={columns}
                    dataSource={data}
                    pagination={false}
                />
                <Pagination className='page'
                    total={total} onChange={onChange} />
            </div>
        </div>
        <Modal
            title="修改"
            visible={editModel}
            onOk={edithideModal}
            onCancel={edithideModal}
            okText="确认"
            cancelText="取消"
            footer={null}
        >
            <Form {...editlayout} form={editForm} name="control-hooks" onFinish={onFinish}>
                <Form.Item
                    name="orName"
                    label="组织名称"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="orType"
                    label="组织类型"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Select
                        // placeholder="请选择创建状态"
                        // value='普通角色'
                        allowClear
                    >
                        <Option value="地区">地区</Option>
                        <Option value="部门">部门</Option>
                        <Option value="处室">处室</Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    name="orNum"
                    label="组织编号"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input></Input>
                </Form.Item>
                <Form.Item
                    name="orCreatetime"
                    label="创建时间"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    name="orUpdatetime"
                    label="更新时间"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                    <Button htmlType="button" onClick={quxiao} style={{ marginLeft: '20px' }}>
                        取消
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    </div>
};
export default OrgTable